import { computed, defineComponent, ref, Transition } from 'vue'
import { PropType } from 'vue'
import './Toast.less'

export type Position = 'top' | 'center' | 'bottom'
export type type = 'success' | 'fail' | 'normal'

export default defineComponent({
	name: 'toast',
	props: {
		show: {
			type: Boolean,
			default: false
		},
		text: {
			type: String,
			required: true
		},
		type: {
			type: String as PropType<type>,
			default: 'normal'
		},
		hideMask: {
			type: Boolean,
			default: false
		},
		position: {
			type: String as PropType<Position>,
			default: 'center'
		},
		duration: {
			type: Number,
			default: 2000
		},
		unmount: {
			type: Function,
			default: () => {}
		}
	},

	setup(props) {
		const show = ref(props.show)

		setTimeout(() => {
			show.value = false
		}, props.duration)

		const contetClass = computed(() => {
			let position = props.position
			let icon = ''
			if (props.type !== 'normal') {
				position = 'center'
				icon = 'icon'
			}
			return ['toast-content', position, icon]
		})

		return () => {
			const Top = () => {
				const icon =
					props.type === 'success' ? (
						<i class="icon iconfont">&#xe62e;</i>
					) : props.type === 'fail' ? (
						<i class="icon iconfont">&#xe692;</i>
					) : (
						''
					)
				return (
					<div
						v-show={props.type && props.type !== 'normal'}
						class="toast-content-icon"
					>
						{icon}
					</div>
				)
			}

			return (
				<Transition name="fade" onAfterLeave={() => props.unmount()}>
					<div class="toast" v-show={show.value}>
						<div v-show={!props.hideMask} class="toast-mask"></div>
						<div class={contetClass.value}>
							{Top()}
							<div class="toast-content-text">{props.text}</div>
						</div>
					</div>
				</Transition>
			)
		}
	}
})
